package org.jeecg.modules.openai.wx;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WechatService {

    @Autowired
    private RedisUtil redisUtil;
    @Value("${open-ai.wechat.appid}")
    private String appId;
    @Value("${open-ai.wechat.secret}")
    private String secret;

    public String getAccessToken() {

        if (redisUtil.get("wechat.api.AccessToken") == null || true) {
            Map<String, Object> parmas = new HashMap<>();
            parmas.put("grant_type", "client_credential");
            parmas.put("appid", appId);
            parmas.put("secret", secret);

            String rp = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", parmas);

            JSONObject jsonObject = new JSONObject(rp);

            if (StringUtils.isNotBlank(jsonObject.getStr("access_token"))) {
                redisUtil.set("wechat.api.AccessToken", jsonObject.getStr("access_token"),5000);
            } else {
                log.error("微信授权错误:{}", jsonObject);
                throw new JeecgBootException("微信授权错误!");
            }
        }


        return (String) redisUtil.get("wechat.api.AccessToken");

    }


    public String getPhone(String code) {

        Map<String, Object> parmas = new HashMap<>();
        parmas.put("code", code);
        JSONObject rq = new JSONObject();
        rq.put("code",code);
        log.info(rq.toString());
        String rp = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken(), rq.toString());
        JSONObject jsonObject = new JSONObject(rp);

        if (StringUtils.isNotBlank(jsonObject.getStr("phone_info"))) {
            return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        } else {
            log.error("获取手机号错误:{}", jsonObject);
            throw new JeecgBootException("获取用户手机号错误!");
        }


    }

    public String getOpenId(String code){

        if(StringUtils.isNotBlank(code)){
            String url="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

            url=url.replaceAll("APPID", appId)
                    .replaceAll("SECRET",  secret)
                    .replaceAll("JSCODE", code);

            JSONObject rp = new JSONObject(HttpUtil.get(url));

            log.info("获取openId：{}",rp);

            return rp.getStr("openid");
        }

        return null;
    }
}
